<?php
define('WP_USE_THEMES', false);
require_once(dirname(__FILE__) . '/../illuminare_wp/wp-load.php');
$_POST      = array_map( 'stripslashes_deep', $_POST );
$_GET       = array_map( 'stripslashes_deep', $_GET );
$_COOKIE    = array_map( 'stripslashes_deep', $_COOKIE );
$_REQUEST   = array_map( 'stripslashes_deep', $_REQUEST );
$wpuser = wp_get_current_user();

function ip_redirectIfNotLoggedIn() {
  if(!ip_isLoggedIn()) {
    header('Location: /wp-login.php?redirect_to=' . $_SERVER['REQUEST_URI']);
    exit;
  } else if (!ip_isAdministrator() && !ip_isEditor()) {
    header('Location: /wp-login.php?message=Please+log+in+as+a+user+with+sufficient+credentials+to+access+that+page.&redirect_to=' . $_SERVER['REQUEST_URI']);
    exit;
  }
}

function ip_redirectIfNotAdministrator($url) {
  if(!ip_isAdministrator()) {
    header("Location: $url");
    exit;
  }
}

function ip_isLoggedIn() {
  global $wpuser;
  return $wpuser->exists();
}

function ip_siteName() {
  global $wpuser;
  $result = array();
  if(strpos($_SERVER['REQUEST_URI'],'/dev-alpha/') !== false) {
    $result[] = 'ALPHA';
  } else if(strpos($_SERVER['REQUEST_URI'],'/dev-beta/') !== false) {
    $result[] = 'BETA';
  }
  if(ip_isAdministrator()) {
    $result[] = 'ADMIN: ' . $wpuser->user_login;
  } else if(ip_isEditor()) {
    $result[] = 'USER: ' . $wpuser->user_login;
  } else {
    $result[] = 'INVALID USER ROLE';
  }
  return implode('<br/>',$result);
}

function ip_logOut() {
  header('Location: ' . wp_logout_url($_SERVER['REQUEST_URI']));
}

function ip_logoutUrl() {
  return wp_logout_url($_SERVER['REQUEST_URI']);
}

function ip_userHasRole($role) {
  global $wpuser;
  return in_array($role,$wpuser->roles);
}

function ip_isAdministrator() {
  return ip_userHasRole('administrator');
}

function ip_isEditor() {
  return ip_userHasRole('illuminare_editor');
}

function ip_isEditorOrAdministrator() {
  return ip_isAdministrator() || ip_isEditor();
}

function ip_tryHiddenPaths($fullPath) {
  if(strpos($fullPath,'/~') !== false) {
    if(file_exists($fullPath)) return $fullPath;
    $testPath = str_replace('/~','/',$fullPath);
    if(file_exists($testPath)) return $testPath;
  }
  $pathArray = explode('/',$fullPath);
  for ($i=1; $i < count($pathArray); $i++) { 
    $pathPart = implode('/',array_slice($pathArray,0,$i));
    $lastPart = $pathArray[$i];
    $exists = $i==(count($pathArray)-1)? file_exists : is_dir;
    if(!$exists("$pathPart/$lastPart")) {
      if(strpos($lastPart,'~')!==0 && $exists("$pathPart/~$lastPart")) {
        $pathArray[$i] = "~$lastPart";
      } else {
        return implode('/',$pathArray);
      }
    }
  }
  return implode('/',$pathArray);
}

function ip_masterDir($path) {
  $result = "library/$path";
  if(ip_isAdministrator()) {
    return ip_tryHiddenPaths($result);
  } else {
    return $result;
  }
}

function ip_allFiles($path) {
  return array_unique(array(ip_userDir($path),ip_masterDir($path)));
}

function ip_hasWriteAccess($path) {
  if(ip_isAdministrator()) return true;
  return strpos($path,ip_userDir(''))===0;
}

function ip_createFile($path) {
  $fullPath = ip_userDir($path);
  $dir = dirname($fullPath);
  
  if(!file_exists($fullPath)) {
    if(!is_dir($dir)) {
      mkdir($dir,0777,true);
    }
    $handle = fopen($fullPath,'a+');
    fclose($handle);
  }
  return $fullPath;
}

function ip_createDir($path) {
  $fullPath = ip_userDir($path);
  if(!is_dir($fullPath)) {
    mkdir($fullPath,0777,true);
  }
  return $fullPath;
}

function ip_userid() {
  global $wpuser;
  return $wpuser->user_login;
}

function ip_recursive_copy($src,$dst) { 
    $dir = opendir($src); 
    @mkdir($dst,0777,true); 
    while(false !== ( $file = readdir($dir)) ) { 
      if (( $file != '.' ) && ( $file != '..' )) { 
        $srcf = "$src/$file";
        $dstf = "$dst/$file";
        if ( is_dir($srcf) ) { 
          ip_recursive_copy($srcf,$dstf); 
        } 
        else { 
          copy($srcf,$dstf); 
        } 
      } 
    } 
    closedir($dir); 
} 

function ip_userDir($path) {
  global $wpuser;
  // for now, administrators will just use the master directory.
  $result = 'library';
  if(ip_isAdministrator()) {
    return ip_tryHiddenPaths("$result/$path");
  } else {
    if(!ip_isEditor()) {
      throw new Exception('Invalid user role for user ' . $wpuser->user_login);
    }
    $result .= '/user/' . $wpuser->user_login;
    if(!is_dir($result)) {
      ip_recursive_copy('library/user-template',$result);
    }
  }
  return "$result/$path";
}

function ip_dirExists($path) {
  foreach (ip_allFiles($path) as $dir) {
    if(is_dir($dir)) {
      return true;
    }
  }
  return false;
}

function ip_firstFile($path) {
  foreach (ip_allFiles($path) as $file) {
    if(file_exists($file))
      return $file;
  }
  return false;
}

function ip_scandir($fullpath) {
  if(!ip_isAdministrator() && strpos($fullpath,'/~')!==FALSE) {
    return Array();
  }
  $result = scandir($fullpath);
  if(ip_isAdministrator()) {
    return $result;
  } else if(ip_isEditor()) {
    $newresult = Array();
    foreach ($result as $i => $value) {
      if($value[0]!='~') {
        $newresult[] = $value;
      }
    }
    return $newresult;
  } else {
    return Array();
  }
}

function ip_scandirs($path) {
  $result = array();
  foreach (ip_allFiles($path) as $dir) {
    if(is_dir($dir)) {
      $result = array_merge($result, ip_scandir($dir));
    }
  }
  return array_unique($result);
}

?>